import CryptoJS from 'crypto-js'
import { encode as base64Encode } from 'js-base64'

// Base64转换
export function toBase64(buffer) {
  const bytes = new Uint8Array(buffer)
  const binaryString = Array.from(bytes, byte => String.fromCharCode(byte)).join('')
  return btoa(binaryString)
}

// 获取WebSocket URL
export function getWebSocketUrl() {
  const url = "wss://iat-api.xfyun.cn/v2/iat"
  const host = "iat-api.xfyun.cn"
  const apiKey = import.meta.env.VITE_API_KEY
  const apiSecret = import.meta.env.VITE_API_SECRET
  const date = new Date().toGMTString()
  const algorithm = "hmac-sha256"
  const headers = "host date request-line"
  const signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2/iat HTTP/1.1`
  const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret)
  const signature = CryptoJS.enc.Base64.stringify(signatureSha)
  const authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
  const authorization = base64Encode(authorizationOrigin)
  return `${url}?authorization=${authorization}&date=${date}&host=${host}`
}